package com.study.ws.config.ws.handler;

import com.study.ws.config.ws.session_manager.ISessionManager;
import com.study.ws.util.ws.WsUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;

/**
 * @author xl-9527
 * @since 2025/3/23
 **/
@Component
public class TextMessageHandler extends TextWebSocketHandler {

    private final Logger log = LoggerFactory.getLogger(TextMessageHandler.class);

    private final ISessionManager<WebSocketSession> iSessionManager;

    public TextMessageHandler(final ISessionManager<WebSocketSession> iSessionManager) {
        this.iSessionManager = iSessionManager;
    }

    @Override
    public void afterConnectionEstablished(final WebSocketSession session) {
        log.info("client connect, and session id is -> {}", session.getId());
        iSessionManager.addSession(session, WsUtil.getUserIdByWebSocketSession(session));
    }

    @Override
    protected void handleTextMessage(final WebSocketSession session, final TextMessage message) throws IOException {
        log.info("receive msg：{} from client, client id is -> {}", message.getPayload(), session.getId());
        for (final WebSocketSession webSocketSession : iSessionManager.getAllSession()) {
            if (webSocketSession != session)
                webSocketSession.sendMessage(new TextMessage("server: i receive message -> [" + message.getPayload() + "]"));
        }
    }

    @Override
    public void afterConnectionClosed(@NonNull final WebSocketSession session, @NonNull final CloseStatus status) {
        iSessionManager.removeSession(WsUtil.getUserIdByWebSocketSession(session));
    }
}
